from flask import (
    Blueprint,
    request,
    g,
    render_template,
)

from exit import db
from .decorators import login_need
from flask_paginate import Pagination, get_page_parameter
from apps.mall.models import *
from .models import CMSRecord
from .forms import *
from apps.mall.forms import DetailForm
from apps.common.models import *
from utils import restful, common_util, api_util
from datetime import datetime
from apps.api.models import *
import requests
import json
from .views_cms import bp
from sqlalchemy import or_
import ast
from decimal import Decimal


@bp.route('/mall/banners/')  # 轮播图
@login_need
def banners():
    page = request.args.get(get_page_parameter(), type=int, default=1)
    status = request.args.get('status')
    status = int(status)
    start = (page - 1) * 10
    end = start + 10
    banner_obj = Banner.query.filter_by(status=status).order_by(Banner.priority)
    banner = banner_obj.slice(start, end)
    bannering = list()
    for i in banner:
        banner_json = i.banner_json()
        goods_category = GoodsCategory.query.filter_by(id=i.goods_id).first()
        if goods_category:
            banner_json['goods_name'] = goods_category.name
        banner_json['create_time'] = i.create_time
        bannering.append(banner_json)

    total = banner_obj.count()
    pagination = Pagination(bs_version=3, page=page, total=total)
    goods = GoodsCategory.query.filter_by(status=0).order_by(GoodsCategory.priority)
    return render_template('cms_mall/banners.html', bannering=bannering, pagination=pagination, goods=goods, status=status)


@bp.route('/mall/banners_info/')    # 轮播信息
@login_need
def banners_info():
    page = request.args.get(get_page_parameter(), type=int, default=1)
    status = request.args.get('status')
    status = int(status)
    start = (page - 1) * 10
    end = start + 10
    banner_obj = Banner.query.filter_by(status=status).order_by(Banner.priority)
    banner = banner_obj.slice(start, end)
    bannering = list()
    for i in banner:
        banner_json = i.banner_json()
        goods_category = GoodsCategory.query.filter_by(id=i.goods_id).first()
        if goods_category:
            banner_json['goods_name'] = goods_category.name
        bannering.append(banner_json)

    total = banner_obj.count()
    return restful.table_success(data=bannering, count=total)


@bp.route('/mall/add_banner/', methods=['POST'])     # 添加轮播图
@login_need
def add_banner():
    form = AddBannerForm(request.form)
    if form.validate():
        name = form.name.data
        image_url = form.image_url.data
        link_url = form.link_url.data
        priority = form.priority.data
        goods_id = form.goods_id.data
        status = form.status.data
        banner_id = form.id.data
        # print(status, '---------')
        if name == 'None' or name == '无' or name == '':
            name = None
        if image_url == 'None' or image_url == '无' or image_url == '':
            image_url = None
        if link_url == 'None' or link_url == '无' or link_url == '':
            link_url = None
        # if goods_id == '无':
        old_banner = Banner.query.filter_by(id=banner_id).first()
        if old_banner:
            old_banner.name = name
            old_banner.image_url = image_url
            old_banner.status = status
            old_banner.link_url = link_url
            old_banner.priority = priority
            cms_record = CMSRecord(cms_id=g.cms_user.id, record='更新轮播图', ip=request.remote_addr)
        else:
            banner = Banner(name=name, image_url=image_url, link_url=link_url, priority=priority, status=status)
            db.session.add(banner)
            cms_record = CMSRecord(cms_id=g.cms_user.id, record='添加轮播图', ip=request.remote_addr)

        db.session.add(cms_record)
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/mall/d_banner/', methods=['POST'])  # 删除轮播图
@login_need
def d_banner():
    banner_id = request.form.get('id')
    if not banner_id:
        return restful.params_error(message=u'请输入banner_id')
    banner = Banner.query.get(banner_id)
    if not banner:
        return restful.params_error(message=u'没有这个轮播图')
    db.session.delete(banner)
    cms_record = CMSRecord(cms_id=g.cms_user.id, record='删除轮播图', ip=request.remote_addr)
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/mall/store_manage/')     # 店铺管理
@login_need
def store_manage():
    status = request.args.get('status')
    return render_template('cms_mall/goods_store.html', status=status)


@bp.route('/mall/store_info/')     # 店铺管理
@login_need
def store_info():
    status = request.args.get('status')
    type_obj = GoodsStore.query.filter(
        # GoodsLabel.status == status,
    ).order_by(GoodsStore.priority)
    page = request.args.get(get_page_parameter(), type=int, default=1)
    start = (page - 1) * 10
    end = start + 10
    data_list = list()
    types = type_obj.slice(start, end)
    total = type_obj.count()
    for i in types:
        data_json = i.store_json()
        data_json['priority'] = i.priority
        data_json['income'] = i.income
        data_json['income_s'] = i.income_s
        data_json['create_time'] = i.create_time.strftime('%Y-%m-%d %H:%M:%S')
        data_list.append(data_json)
    return restful.table_success(data=data_list, count=total)


@bp.route('/mall/update_store/', methods=['POST'])    # 更新店铺
@login_need
def update_store():
    form = UpdateStoreForm(request.form)
    if form.validate():
        name = form.name.data
        content = form.content.data
        store_img = form.store_img.data
        store_id = form.store_id.data
        priority = form.priority.data

        # print(label_id)
        goods_store = GoodsStore.query.filter_by(id=store_id).first()
        if goods_store:
            goods_store.name = name
            goods_store.store_img = store_img
            goods_store.content = content
            goods_store.priority = priority
            # goods_store.status = status
            record = '更新 <{}> 店铺'.format(goods_store.name)
        else:
            create_goods_store = GoodsStore(name=name, store_img=store_img, priority=priority, content=content)
            db.session.add(create_goods_store)
            record = '添加 <{}> 店铺'.format(name)

        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
        db.session.add(cms_record)
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/mall/update_store_income/', methods=['POST'])  # 更新店铺收益
@login_need
def update_store_income():
    income = request.form.get('income')
    store_id = request.form.get('store_id')
    if not all([income, store_id]):
        return restful.params_error(message='请传入参数')
    goods_store = GoodsStore.query.filter_by(id=store_id).with_for_update().first()
    if goods_store is None:
        return restful.params_error(message='未找到店铺')
    income = Decimal(income)
    # 修改店铺余额
    if goods_store.income != income:
        record = '{}店铺余额 <{}>----->修改为 {}'.format(goods_store.name, goods_store.income, income)
        goods_store.income = income
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
        db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/mall/del_store/', methods=['POST'])    # 删除店铺
@login_need
def del_store():
    store_id = request.form.get('store_id')
    goods = GoodsStore.query.filter_by(id=store_id).first()
    if goods is None:
        return restful.params_error(message='未找到店铺')
    db.session.delete(goods)
    record = '删除 <{}> 店铺'.format(goods.name)
    cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/mall/type_manage/')     # 类型管理
@login_need
def type_manage():
    return render_template('cms_mall/types.html')


@bp.route('/mall/category_info/')     # 类型管理
@login_need
def category_info():
    type_obj = GoodsCategory.query.filter(
        GoodsCategory.status == 0, GoodsCategory.id != 7, GoodsCategory.id != 8
    ).order_by(GoodsCategory.priority)
    page = request.args.get(get_page_parameter(), type=int, default=1)
    start = (page - 1) * 10
    end = start + 10
    types = type_obj.slice(start, end)
    total = type_obj.count()
    category_list = list()
    for i in types:
        type_json = i.goods_category_json()
        type_json['type_id'] = i.id
        type_json['big_img'] = i.big_img or '无'
        category_list.append(type_json)
    return restful.table_success(data=category_list, count=total)


@bp.route('/mall/update_type/', methods=['POST'])     # 更新类型
@login_need
def update_type():
    form = UpdateType(request.form)
    if form.validate():
        name = form.name.data
        small_img = form.small_img.data
        # big_img = form.big_img.data
        priority = form.priority.data
        # status = form.status.data
        type_id = form.type_id.data

        goods_type = GoodsCategory.query.filter_by(id=type_id).first()
        if goods_type is None:
            create_type = GoodsCategory(name=name, small_img=small_img, priority=priority)
            db.session.add(create_type)
            record = '添加 <{}> 商品类型'.format(name)
        else:
            goods_type.name = name
            goods_type.small_img = small_img
            # goods_type.big_img = big_img
            goods_type.priority = priority
            record = '更新 <{}> 商品类型'.format(goods_type.name)
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
        db.session.add(cms_record)
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/mall/del_type/', methods=['POST'])    # 删除类型
@login_need
def del_type():
    type_id = request.form.get('type_id')
    goods = GoodsCategory.query.filter_by(id=type_id).first()
    if goods is None:
        return restful.params_error(message='未找到商品类型')
    if goods.id == 7 or goods.id == 8:
        return restful.params_error(message='推荐好物和精选好物不能修改')
    record = '删除 <{}> 商品类型'.format(goods.name)
    db.session.delete(goods)
    cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/mall/goods_manage/')  # 商品管理
@login_need
def goods_manage():
    type_id = request.args.get('type_id')
    status = request.args.get('status')
    goods_name = request.args.get('goods_name')
    goods_label = GoodsCategory.query.order_by(GoodsCategory.priority).all()

    content = {
        'type_id': type_id,
        'status': status,
        'goods_label': goods_label,
        'goods_name': goods_name,
    }
    return render_template('cms_mall/goods.html', **content)


@bp.route('/mall/goods_info/')     # 商品信息
@login_need
def goods_info():

    page = request.args.get(get_page_parameter(), type=int, default=1)
    start = (page - 1) * 10
    end = start + 10

    goods_name = request.args.get('goods_name')
    status = request.args.get('status')
    # type_id = request.args.get('type_id')

    filters = list()
    filters.append(Goods.status == status)

    if goods_name:
        filters.append(Goods.name.like("%" + str(goods_name) + "%"))

    goods_obj = Goods.query.filter(*filters)
    goods = goods_obj.order_by(Goods.priority).slice(start, end)
    goods_list = list()
    for i in goods:
        goods_json = i.goods_json()

        goods_json['integral'] = i.integral
        goods_list.append(goods_json)
    total = goods_obj.count()

    return restful.table_success(data=goods_list, count=total)


@bp.route('/mall/update_goods/', methods=['POST'])    # 添加商品
@login_need
def update_goods():
    form = AddGoodsForm(request.form)
    if form.validate():
        name = form.name.data
        # goods_img = form.goods_img.data
        # integral = form.integral.data
        price = form.price.data
        stock_c = form.stock_c.data
        goods_code = form.goods_code.data
        priority = form.priority.data
        status = form.status.data
        fees = form.fees.data
        low_price = form.low_price.data
        high_price = form.high_price.data

        goods_id = form.goods_id.data
        is_show = 0

        goods = Goods.query.filter_by(id=goods_id).first()
        if goods:
            goods.name = name
            # goods.goods_img = goods_img
            goods.freight = 0
            goods.price = price
            goods.goods_code = goods_code
            # goods.integral = integral
            goods.stock_c = stock_c
            # goods.sku = sku
            goods.priority = priority
            goods.low_price = low_price
            goods.high_price = high_price
            goods.fees = fees
            # goods.status = status
            # goods.category_id = goods_type

            record = '更新 <{}> 拍品'.format(goods.name)
        else:
            create_goods = Goods(
                name=name, old_price=0,
                price=price, priority=priority, stock_t=stock_c,
                stock_c=stock_c,
                freight=0,
                # sku=sku,
                status=status,
                # pay_type=data_id,
                # category_id=goods_type,
                integral=0,
                is_show=is_show,
                # store_id=g.cms_user.store_id
                goods_code=goods_code,
                low_price=low_price,
                high_price=high_price,
                fees=fees,
            )
            db.session.add(create_goods)
            db.session.commit()

            record = '添加 <{}> 拍品'.format(name)
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
        db.session.add(cms_record)
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/mall/del_goods/', methods=['POST'])    # 删除商品
@login_need
def del_goods():
    goods_id = request.form.get('goods_id')
    goods = Goods.query.filter_by(id=goods_id).first()
    if goods is None:
        return restful.params_error(message='未找到商品')
    goods_detail = GoodsDetail.query.filter_by(goods_id=goods_id).all()
    for i in goods_detail:
        db.session.delete(i)
    db.session.delete(goods)

    record = '删除 <{}> 商品'.format(goods.name)
    cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/mall/goods_detail_manage/')  # 商品详情管理
@login_need
def goods_detail_manage():
    goods_id = request.args.get('goods_id')

    return render_template('cms_mall/goods_detail.html', goods_id=goods_id)


@bp.route('/mall/goods_detail_info/')  # 商品详情信息
@login_need
def goods_detail_info():
    goods_id = request.args.get('goods_id')
    detail_obj = GoodsDetail.query.filter_by(goods_id=goods_id).order_by(GoodsDetail.status, GoodsDetail.priority)
    page = request.args.get(get_page_parameter(), type=int, default=1)
    start = (page - 1) * 10
    end = start + 10
    goods_detail = detail_obj.slice(start, end)
    detail_list = list()
    for i in goods_detail:
        detail_json = i.goods_detail_json()
        goods = Goods.query.filter_by(id=i.goods_id).first()
        if i.status == 0:
            detail_json['status_name'] = '商品详情<轮播>'
        else:
            detail_json['status_name'] = '商品详情<内容>'
        detail_json['goods_name'] = goods.name
        detail_json['data_id'] = i.status
        detail_json['detail_id'] = i.id
        detail_list.append(detail_json)
    total = detail_obj.count()
    return restful.table_success(data=detail_list, count=total)


@bp.route('/mall/update_detail/', methods=['GET', 'POST'])    # 更新商品详情
@login_need
def update_detail():
    form = UpdateDetail(request.form)
    if form.validate():
        goods_id = form.goods_id.data
        goods_img = form.goods_img.data
        status = form.data_id.data
        priority = form.priority.data
        detail_id = form.detail_id.data
        goods = Goods.query.filter_by(id=goods_id).first()
        if goods is None:
            return restful.params_error(message='未找到商品')

        if status == 0:
            detail_type = '轮播'
        else:
            detail_type = '内容'

        goods_detail = GoodsDetail.query.filter_by(id=detail_id).first()
        if goods_detail is None:
            create_detail = GoodsDetail(goods_id=goods.id, goods_img=goods_img, status=status, priority=priority)
            db.session.add(create_detail)
            record = '添加 <{}> 商品{}详情'.format(goods.name, detail_type)
        else:
            goods_detail.goods_img = goods_img
            goods_detail.status = status
            goods_detail.priority = priority
            record = '更新 <{}> 商品{}详情'.format(goods.name, detail_type)

        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
        db.session.add(cms_record)
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/mall/del_detail/', methods=['POST'])   # 删除商品详情
@login_need
def del_detail():
    detail_id = request.form.get('detail_id')
    goods_detail = GoodsDetail.query.filter_by(id=detail_id).first()
    if goods_detail is None:
        return restful.params_error(message='未找到商品详情')
    db.session.delete(goods_detail)
    goods = Goods.query.filter_by(id=goods_detail.goods_id).first()

    if goods_detail.status == 0:
        detail_type = '轮播'
    else:
        detail_type = '内容'
    record = '删除 <{}> 商品{}详情'.format(goods.name, detail_type)
    cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/mall/goods_to_type/', methods=['POST'])   # 商品显示其他页面
@login_need
def goods_to_type():
    show_id = request.form.get('show_id')
    status = request.form.get('status')
    is_type = request.form.get('is_type')
    if status == '0':
        goods_label = GoodsCategory.query.filter_by(id=show_id).first()
        if goods_label is None:
            return restful.params_error(message='未找到商品标签')
        goods_label.is_type = is_type
        goods_all = Goods.query.filter_by(label_id=goods_label.id).all()
        for i in goods_all:
            i.is_type = is_type
    else:
        goods = Goods.query.filter_by(id=show_id).first()
        if goods is None:
            return restful.params_error(message='未找到商品')
        goods.is_type = is_type
    db.session.commit()
    return restful.success()

